<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []
const forFees = proxy.$Fees || []

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = {
  info: '严禁发布暴力、涉黄等违法内容',
  // ----
  opportFeeId: 'publishBusi',
  opportFeeUse: true
}
// ----
const cates = ref([])
const myCityData = proxy.$City
// ----
const advs = reactive({
  add: true,
  maxnum: 0,
  forFree: 1,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})
// ----
let forSortNum = 0
// ----
const form = reactive({
  tabName: 'market_opport',
  status: 0,
  // ----
  name: '',
  desc: '',
  cateTxt: '',
  cate: 0,
  addrCity: '',
})

/* ---- */
const pickerCate = ref()
const pickerCity = ref()
const uploadoss = ref()
const layer = ref()
const layerLoading = ref()

/* ---- */
const getFormInfo = async () => {
  advs.setTrueStyle = { height: `${document.querySelector('.squareBox dl dd label').clientWidth / advs.forFree}px` }
  // --获取购买市场营销信息--
  forFees.some((item) => {
    if (String(item.id) === String(user.opportFeeId)) user.opportFeeUse = item.isOpenUse
  })
  // --获取发现商机分类--
  const oppCateItems = forSys.filter((item) => { return String(item.name) === 'market_opport_cate' })
  if (Number(oppCateItems.length) === 1) {
    await proxy.$Myfun.getJsonData(oppCateItems[0].value, (resJson) => {
      const cateItems = []
      resJson[0].list.forEach((item, index) => {
        cateItems.push({
          value: String(item.id),
          text: proxy.$Myfun.setText(item.name)
        })
      })
      cates.value = cateItems
    })
  }
  // -- 获取商机设置信息 --
  const newItems = forSys.filter((item) => { return String(item.name) === form.tabName })
  if (Number(newItems.length) === 1) {
    proxy.$Myfun.getJsonData(newItems[0].value, (resJson) => {
      const RJData = resJson[0] || {}
      // ----
      if (({}).hasOwnProperty.call(RJData, 'opp_status')) form.status = RJData.opp_status
    })
  }
  // -- 获取商机信息 --
  if (proxy.$route.query.id) {
    const forOpportData = { params: { 'OpportSearch[id]': proxy.$route.query.id } }
    await proxy.$Axios.all([
      proxy.$Axios.get('opport/index', forOpportData)
    ]).then(proxy.$Axios.spread((opportData) => {
      const OData = opportData.items[0] || {}
      // ----
      form.name = OData.name
      form.desc = OData.description
      // ----
      form.cate = OData.business_cate_id
      cates.value.some((current) => {
        if (String(current.value) === String(OData.business_cate_id)) form.cateTxt = current.text
      })
      // ----
      const forCity = OData.citys.split(',')
      form.addrCity = forCity[1] + ' - ' + forCity[2] + ' - ' + forCity[3]
      // ----
      proxy.$Myfun.getJsonData(OData.image, (resJson) => {
        resJson.forEach((item) => {
          advs.imgs.push({
            imgName: item.name,
            imgUrl: item.image,
            imgW: item.width,
            imgH: item.height
          })
        })
        if (Number(advs.imgs.length) >= Number(advs.maxnum) && Number(advs.maxnum) > 0) advs.add = !advs.add
      })
    })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
}
// --上传图片操作--
const uploadAct = (type, selectObj, event, index) => {
  const uploadOss = uploadoss.value
  switch (Number(type)) {
    case 1: {
      uploadOss.uploadImg(event, selectObj,'imgs', index)
      break
    }
    case 2: {
      uploadOss.delInfo(selectObj, event)
      break
    }
    case 3: {
      uploadOss.uploadImgMoreWX(selectObj)
      break
    }
  }
}
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
}
// ----
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      const options = {
        type: 1,
        button: ['取消', '确定'],
        initData: cates.value,
        yes: (result) => {
          const RJData = result[0] || {}
          form.cateTxt = RJData.text
          form.cate = RJData.value
        }
      }
      proxy.$Myfun.isIndepth(pickerCate.value, 'open', options)
      break
    }
    case 2: {
      const options = {
        type: 3,
        button: ['取消', '确定'],
        initData: myCityData,
        yes: (result) => {
          let resText = ''
          result.forEach((curItem, index) => {
            resText += (index > 0 ? ' - ' : '') + curItem.text
          })
          form.addrCity = resText
        }
      }
      proxy.$Myfun.isIndepth(pickerCity.value, 'open', options)
      break
    }
  }
}
// ----
const setPublicInfo = async (item, callback) => {
  await proxy.$http[item.type](item.url, item.data).then((res) => {
    if (res) callback && callback(res)
  }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
}
const subform = async () => {
  if (Number(form.name.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写标题名称！')
    return false
  }
  if (Number(form.cateTxt.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请选择分类！')
    return false
  }
  if (Number(form.addrCity.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请选择地区！')
    return false
  }
  // ----
  let forAdvs = ''
  if (Number(advs.imgs.length) > 0) {
    const advItems = []
    advs.imgs.forEach((item, index) => {
      advItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
    forAdvs = JSON.stringify(advItems)
  }
  // ----
  const forCity = ',' + form.addrCity.replace(/ - /g, ',') + ','
  // --获取排序--
  const forSortData = {
    params: {
      sort: 'SORT_DESC',
      // ----
      page: 1,
      PageSize: 1
    }
  }
  await proxy.$Axios.all([
    proxy.$Axios.get('opport/index', forSortData)
  ]).then(proxy.$Axios.spread((sortData) => {
    if (Number(sortData.items.length) > 0) forSortNum = sortData.items[0].sort_num
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  let forType = 'post'
  let forUrl = 'opport/create'
  let forData = {
    dealer_id: logUser.id,
    is_show: 1,
    // --默认审核状态--
    status: form.status,
    // ----
    sort_num: Number(forSortNum + 1),
    // ----
    name: form.name,
    description: form.desc,
    business_cate_id: form.cate,
    citys: forCity,
    image: forAdvs,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  if (proxy.$route.query.id) {
    forType = 'patch'
    forUrl = 'opport/update?id=' + proxy.$route.query.id
    forData = {
      name: form.name,
      description: form.desc,
      business_cate_id: form.cate,
      citys: forCity,
      image: forAdvs,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
  if (resData) {
    if (user.opportFeeUse) {
      // --增加发布商机记录--
      await setPublicInfo({
        type: 'post',
        url: 'opport-has-dealer/create',
        data: {
          dealer_id: logUser.id,
          opport_id: resData.id,
          // ----
          config_id: userInfo.config_id,
          openid: userInfo.openid
        }
      })
      // --修改当前用户发布商机数--
      await setPublicInfo({
        type: 'patch',
        url: 'dealer/update?id=' + logUser.id,
        data: {
          opport_views: Number(logUser.opport_views) - 1,
          // ----
          config_id: userInfo.config_id,
          openid: userInfo.openid
        }
      })
    }
    // ----
    proxy.$router.back()
  }
}
const goback = () => { proxy.$router.back() }

/* ---- */
onMounted(() => {
  getFormInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="xw-msg xw-color-5 xw-bgCL-19" v-html="user.info"></div>
    <div class="formSet">
      <ul>
        <li>
          <div class="form-are xw-radius-3">
            <h1>标题名称</h1>
            <p><textarea class="tarea-H3" placeholder="" v-model.trim="form.name"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>文字描述</h1>
            <p><textarea class="tarea-H5" placeholder="" v-model.trim="form.desc"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>选择分类</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.cateTxt" @click="getAuditFun(1)" readonly unselectable="on" onfocus="this.blur()"/></p>
            <span class="fa fa-caret-down xw-color-16"></span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.cateTxt"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>选择地区</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model="form.addrCity" @click="getAuditFun(2)" readonly unselectable="on" onfocus="this.blur()"/></p>
            <span class="fa fa-caret-down xw-color-16"></span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.addrCity"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-imgs xw-radius-3 squareBox">
            <div class="FIS-top xw-flex xw-flex-align xw-flex-justify">
              <span class="FIS-title">图文介绍</span>
              <span v-if="Number(advs.maxnum) > 0">数量：最多{{advs.maxnum}}张</span>
            </div>
            <dl class="FIS-img xw-float">
              <dd class="xw-float-W3" v-for="(item, index) in advs.imgs"><label class="xw-block xw-act" :style="advs.setTrueStyle"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.imgUrl + ')' }"></div><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, advs, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, advs, index)"></span></dd>
              <dd class="xw-float-W3" v-if="advs.add"><label class="xw-act xw-flex xw-flex-center" :style="advs.setTrueStyle" @click="uploadAct(3, advs)"><em class="fal fa-plus"></em></label></dd>
            </dl>
          </div>
        </li>
      </ul>
      <div class="form-sub xw-radius-3 xw-bgCL-11 xw-act" @click="subform">确定提交</div>
      <div class="form-sub xw-radius-3 xw-WhiteRed xw-act" @click="goback">取消返回</div>
    </div>
    <picker-view ref="pickerCate"/>
    <picker-view ref="pickerCity"/>
    <uploadoss-view ref="uploadoss"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>

<style scoped>
/* ---- */
.xw-msg { padding: 0.8rem 1.2rem; }
</style>